/* JS
*	Simple full browser background image Jquery plugin.
*	Copyright 2011 http://thereformation.co.nz
*	@Version	0.2 Beta
*	@author		Dale Sattler
*	@link		http://thereformation.co.nz

	This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

(function( $ ){
		var img_prop;
		var imageArray = [];
		var targetContainer;
		var defaults;
		var firstLoad = true;
		var transitionName;
		
		var methods = {
			init : function(options, imgPath ) {
			defaults = {
				fadeInSpeed: 1000,				// [integer] speed in milliseconds for the image to fade
				center: true,					// [boolean] whether or not to center the image within it's container
				ieSmooth:false					// [boolean] turns on image smoothing for IE 6, 7, 8. May affect performance
			};
			
			targetContainer = $(this);
			
			if(options){
				$.extend(defaults, options);
			}
			

			transitionName = FirstSupportedPropertyName(["transition", "msTransition", "MozTransition", "WebkitTransition", "OTransition"]);
			
			//create image
			var img  = new Image();
			//add to array
			imageArray.unshift(img);
			
			if(firstLoad === true) {
				if(transitionName){
					$(targetContainer).css({
						'opacity' : '0'
					});
				}else{
					$(targetContainer).fadeTo(0);
				}
			}

			$(img).load(function () {
				$(img).css({filter: 'alpha(opacity=0)', opacity: '0', left:0, top: 0, position: 'absolute', 'z-index': -100});
				if(defaults.ieSmooth) {
					$(img).css({
						'-ms-interpolation-mode' : 'bicubic'
					});
				}
				//add image to container
				$(targetContainer).append(img);
				//resize image
				resizeImg($(window).width(), $(window).height(), $(img).width(), $(img).height());
				
				if(firstLoad === true) {
					firstLoad = false;
					if(transitionName){
						$(targetContainer).css({
							'opacity' : '1'
						});
					}else{
						$(targetContainer).fadeTo(1);
					}
				}
				
				doFadeTransition(img);
	
				}).error(function () {
					// got an error
				alert('image not loaded');
				}).attr('src', imgPath + '?random=' + (new Date()).getTime());


			$(window).bind('resize.refFullBgImg', methods.resizeBg);
			return this;
	
			},
			resizeBg : function() {
				resizeImg($(window).width(), $(window).height(), $(imageArray[0]).width(), $(imageArray[0]).height());
			},
			destroy: function() {
				$(window).unbind('.refFullBgImg');
			}
		};

		$.fn.refFullBgImg = function( method ) {		
			if ( methods[method] ) {
			  return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
			} else if ( typeof method === 'object' || ! method ) {
			  return methods.init.apply( this, arguments );
			} else {
			  $.error( 'Method ' +  method + ' does not exist on jQuery.refSlidePanel' );
			}
		};
		
		
		function doFadeTransition(target) {	
			if (transitionName) {
				var speed = defaults.fadeInSpeed / 1000 + 's';
				target.addEventListener( 'webkitTransitionEnd', function(e) { cleanUp(target); }, false );
				target.addEventListener( 'oTransitionEnd', function(e) { cleanUp(target); }, false );
				target.addEventListener( 'transitionend', function(e) { cleanUp(target); }, false );
				target.addEventListener( 'MSTransitionEnd', function(e) { cleanUp(target); }, false );
							
				target.style.opacity = 1;
				target.style[transitionName + "Property"] = "opacity";
				target.style[transitionName + "Duration"] = speed;
				target.style[transitionName + "Delay"] = "0s";

			}else{
				$(target).fadeTo(defaults.fadeInSpeed,1, function() {
					cleanUp(target);
				});
			}
		}
		
		function cleanUp(target){
			if (transitionName) {
				target.removeEventListener( 'webkitTransitionEnd', function(e) { cleanUp(target); }, false );
				target.removeEventListener( 'oTransitionEnd', function(e) { cleanUp(target); }, false );
				target.removeEventListener( 'transitionend', function(e) { cleanUp(target); }, false );
				target.removeEventListener( 'MSTransitionEnd', function(e) { cleanUp(target); }, false );
			}
				
			if(imageArray.length > 1) {
				imageArray.pop();
				$(targetContainer).children().eq(0).remove();
			}

			if( typeof defaults.callback == 'function' ){
				defaults.callback.call(this, targetContainer, defaults);
			}
		}
				
		function resizeImg(sw, sh, imgw, imgh, targetContainer){
			if ((sh / sw) > (imgh / imgw)) {
					img_prop = imgw/imgh;
					destHeight = sh;
					destWidth = sh * img_prop;
				} else {
					img_prop = imgh/imgw;
					destWidth = sw;
					destHeight = sw * img_prop;
				}

			$(imageArray[0]).attr({
				width: destWidth,
				height: destHeight
			});
			
			if(defaults.center) {
				var xVal = sw * .5 - $(imageArray[0]).width() * .5;
				var yVal = sh * .5 - $(imageArray[0]).height() * .5;
				$(imageArray[0]).css({left:xVal, top: yVal});
			}
		}
		
		function FirstSupportedPropertyName(prefixedPropertyNames) {
			var tempDiv = document.createElement("div");
			for (var i = 0; i < prefixedPropertyNames.length; ++i) {
				if (typeof tempDiv.style[prefixedPropertyNames[i]] != 'undefined')
					return prefixedPropertyNames[i];
				}
			return null;
		}

})( jQuery );